package com.example.jpademo;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Component;

/**
 * 主题事件发送
 */
@Component
public class TopicEventPublisher implements ApplicationEventPublisherAware, ApplicationContextAware {

    private ApplicationContext applicationContext;
    private ApplicationEventPublisher applicationEventPublisher;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }

    public void publishEvent(String topic){
        if("A".equals(topic)){
            applicationEventPublisher.publishEvent(new Event_A(applicationContext));
        }else if("B".equals(topic)){
            applicationEventPublisher.publishEvent(new Event_B(applicationContext));
        }else {
            throw new RuntimeException("未知事件");
        }
    }
}
